<template>
	<view class="product-page">
		<!-- 商品图片轮播 -->
		<swiper class="product-swiper" indicator-dots="true" autoplay="false" interval="3000" duration="300">
			<swiper-item v-for="(img, index) in product.imageUrl" :key="index" class="swiper-item">
				<image :src="img" mode="aspectFill" class="image"></image>
			</swiper-item>
		</swiper>

		<!-- 商品信息 -->
		<view class="product-info">
			<!-- 价格 -->
			<text class="price">￥{{ product.goodsPrice }}</text>
		</view>
		<view class="product-info">
			<!-- 商品名 -->
			<text class="name">{{ product.goodsName }}</text>
			<!-- 重量 -->
			<text class="specification">{{ product.specification }}/份</text>
		</view>

		<!-- 标签和亮点 -->
		<view class="tags">
			<view class="tag">{{ product.tags }}</view>
		</view>
		<view class="highlights">
			<view v-for="(highlight, index) in product.highlights" :key="index" class="highlight">{{ highlight }}</view>
		</view>

		<!-- 评论区，包含折叠 -->
		<view class="reviews">
			<text class="reviews-title">商品评价 ({{ product.reviews.length }}+)</text>
			<text class="review-meta" @click="commentOnCommodity">全部</text>
			<view v-for="(review, index) in visibleReviews" :key="index" class="review">
				<view class="review-header">
					<text class="review-user">{{ review.user }}</text>
				</view>
				<view class="stars">
					<!-- 商品评价星级 -->
					<text v-for="n in review.rating" :key="n" class="star">★</text>
				</view>
				<text class="review-text">{{ review.comment }}</text>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="order-status">
				<!-- 收藏按钮 -->
				<view class="status-item" @click="toggleFavorite" :class="{ animate: isFavoriteClicked }">
					<image v-if="!isFavoriteClicked" src="/static/motif/shoucang1.png" class="order-icon" />
					<image v-if="isFavoriteClicked" src="/static/motif/shoucang2.png" class="order-icon" />
					<text class="status-text">收藏</text>
				</view>

				<!-- 购物车按钮 -->
				<view class="status-item" @click="toggleCart" :class="{ animate: isCartClicked }">
					<image v-if="!isCartClicked" src="/static/motif/jiarugouwuche1.png" class="order-icon" />
					<image v-if="isCartClicked" src="/static/motif/jiarugouwuche2.png" class="order-icon" />
					<text class="status-text">加入购物车</text>
				</view>
			</view>
			<button class="btn-buy" @click="buyNow">立即购买</button>
		</view>

		<!-- 弹窗遮罩层 -->
		<view v-if="showPopup" class="mask" @click="closePopup"></view>
		<!-- 弹窗内容 -->
		<view v-if="showPopup" class="popup">
			<view class="popup-header">
				<text class="popup-title">选择规格</text>
				<text class="popup-close" @click="closePopup">×</text>
			</view>
			<!-- 规格 -->
			<view class="popup-content">
				<view class="popup-option" v-for="(option, index) in product.options" :key="index">
					<text class="option-name">{{ option.name }}</text>
					<view class="option-values">
						<text v-for="(value, i) in option.values" :key="i"
							:class="['option-value', selectedOptions[index] === i ? 'selected' : '']" @click="selectOption(index, i)">
							{{ value }}
						</text>
					</view>
				</view>
			</view>
			<!-- 增减商品按钮 -->
			<view class="quantity-selector">
				<button @click="decrement" class="quantity-btn minus">-</button>
				<!-- 数量 -->
				<text class="quantity-value">{{ product.goodsQuantity }}</text>
				<button @click="increment" class="quantity-btn plus">+</button>
			</view>
			<view class="popup-footer">
				<button class="btn-confirm" @click="confirmPurchase">确认购买</button>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		findAllGoods,
		findAllEvalue
	} from '../../api/tome.js'
	import {
		addCar,
		addCollect,
	} from '@/api/shopping.js';
	import request from '../../request/index.js';
	export default {
		data() {
			return {
				product: {
					goodsPrice: '9.99', //价格
					goodsName: '新葡萄', //商品名字
					// specification: '250g',
					tags: '果肉细腻，清甜可口，颗粒饱满', //详情
					// highlights: ['称重退差价', '支持售后', '清甜'], //亮点
					imageUrl: [],
					goodsQuantity: 1, // 默认选择数量为 1
					reviews: [],
					images: [],
					options: [],
				},
				showAllReviews: false, //展示评论
				isFavoriteClicked: false, // 控制收藏按钮状态
				isCartClicked: false, // 控制购物车按钮状态
				showPopup: false, //弹窗
				selectedOptions: [], // 存储用户选择的规格
				goodsQuantity: "1", // 默认选择数量为 1
			};
		},
		computed: {
			//展示评价条数
			visibleReviews() {
				return this.showAllReviews ? this.product.reviews : this.product.reviews.slice(0, 3);
			},
		},
		// 后端接口调取商品详情
		onLoad() {

		},
		created() {
			this.selectGoods()
			this.selectEvalue()
		},
		methods: {
			// 加载商品信息
			selectGoods() {
				// 获取商品id
				let goodId = this.$cookies.get("goodsId");
				// 进行页面显示
				findAllGoods({
					goodsId: goodId
				}).then(request => {
					// 商品信息集合（包括规格信息）
					const goodsInfoCollection = request.data.map(item => {
						const goods = {
							goodsId: item.goodsId,
							goodsName: item.goodsName,
							goodsPrice: item.goodsPrice,
							goodsUrl: item.goodsUrl,
							goodsInfo: item.goodsInfo
						};
						const specs = item.goodsSpecs.map(spec => {
							return {
								goodsSpecsId: spec.goodsSpecsId,
								goodsSpecsName: spec.goodsSpecsName,
								goodsSpecsPrice: spec.goodsSpecsPrice,
								goodsSpecsNum: spec.goodsSpecsNum
							};
						});
						// 将规格信息添加到商品对象中
						goods.specs = specs; // 将 specs 数组添加到 goods 对象中
						this.product.options = item.goodsSpecs;
						return goods;
					});
					console.log(request.data)
					console.log('商品信息集合（包括规格信息）:', goodsInfoCollection);

					// 遍历 goodsInfoCollection 并找到特定的商品信息
					this.product.goodsId = goodsInfoCollection[0].goodId;
					this.product.tags = goodsInfoCollection[0].goodsInfo;
					this.product.goodsName = goodsInfoCollection[0].goodsName;
					this.product.goodsPrice = goodsInfoCollection[0].goodsPrice;
					this.product.imageUrl = goodsInfoCollection[0].goodsUrl.split(', ');
					console.log("图片", this.product.goodsUrl)
					console.log("规格信息1:", this.product.options);
				})
			},

			// 获取评论
			selectEvalue() {
				// 获取商品id
				let goodId = this.$cookies.get("goodsId");
				// 进行页面显示
				findAllEvalue({
					goodsId: goodId
				}).then(request => {
					console.log(request.data)
					// 转换数据格式
					const reviews = request.data.map(evalItem => {
						return {
							user: evalItem.tuser[0].userName, // 提取用户名
							rating: null, // 原始数据中没有评分，所以这里设为 null 或者根据需要进行计算
							comment: evalItem.comment // 提取评论
						};
					});
					this.product.reviews = reviews;
					// 输出结果
					console.log(reviews);
					console.log("集合", this.reviews);
				})
			},

			// 跳转到商品评价页面
			commentOnCommodity() {
				uni.navigateTo({
					url: '/pages/profile/appraise'
				});
			},

			// 跳转到订单确认页面
			confirmPurchase() {
				// 构建商品信息对象
				const productInfo = {
					id: this.product.id,
					imageUrl: this.product.imageUrl, //商品图
					goodsName: this.product.goodsName, //商品名字
					goodsPrice: this.product.goodsPrice, //商品价格
					goodsQuantity: this.product.goodsQuantity, //商品数量
					options: this.product.specificationName, //规格
					selectedSpecs: this.selectedOptions.map(
						(optionIndex, i) => this.product.options[i].values[optionIndex]
					),
					quantity: this.quantity
				};
				// 将对象转为 JSON 字符串并 URL 编码
				const productInfoStr = encodeURIComponent(JSON.stringify(productInfo));
				// 跳转页面并附加商品信息
				uni.navigateTo({
					url: `/pages/profile/acknowledgementOfOrder?productInfo=${productInfoStr}`
				});
			},
			//跳转订单确认页面
			confirmPurchase() {
				uni.navigateTo({
					url: '/pages/profile/acknowledgementOfOrder'
				})
			},

			// 点击收藏按钮
			toggleFavorite() {
				this.isFavoriteClicked = !this.isFavoriteClicked;
				addCollect({
					userId: this.$cookies.get("id"),
					goodsId: this.$cookies.get("goodsId")
				}).then(res => {
					if (res.meeeage == "添加收藏成功") {
						uni.showToast({
							title: '已添加收藏',
							icon: 'success',
						})
					} else if (res.message == "添加收藏失败") {
						uni.showToast({
							title: '已添加收藏',
							icon: 'error',
						})
					} else if (res.message == "已经在收藏里面了") {
						uni.showToast({
							title: '已添加收藏',
							icon: 'error',
						})
					}
				})
			},
			// 点击加入购物车按钮时切换状态
			toggleCart() {
				this.isCartClicked = !this.isCartClicked;
				addCar({
					userId: this.$cookies.get("id"),
					goodsId: this.$cookies.get("goodsId"),
					goodsName: this.$cookies.get("goodsName"),
					goodsNum: this.goodsQuantity,
				}).then((res) => {
					uni.showToast({
						title: '已添加购物车',
						icon: 'success',
					});
				})
			},
			// 点击立即购买显示弹窗
			buyNow() {
				this.showPopup = true;
				this.selectedOptions = new Array(this.product.options.length).fill(null);
			},
			// 关闭弹窗
			closePopup() {
				this.showPopup = false;
			},
			// 选择规格
			selectOption(optionIndex, valueIndex) {
				this.$set(this.selectedOptions, optionIndex, valueIndex);
			},
			//增加商品按钮
			increment() {
				this.product.goodsQuantity++;
			},
			//减少商品按钮
			decrement() {
				if (this.product.goodsQuantity > 1) {
					this.product.goodsQuantity--;
				}
			},
			// 点击立即购买时显示弹窗并初始化数量
			buyNow() {
				this.showPopup = true;
				this.selectedOptions = new Array(this.product.options.length).fill(null);
				this.product.goodsQuantity = 1; // 重置数量为 1
			},
		}
	};
</script>

<style>
	.product-page {
		background-color: #ffffff;
		padding-bottom: 100rpx;
	}

	/* 轮播图 */
	.product-swiper {
		width: 100%;
		height: 550rpx;
		/* 调整图片高度 */
	}

	.swiper-item,
	.image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
	}

	.product-info {
		padding: 20rpx;
	}

	.price {
		color: #e60012;
		font-weight: bold;
		font-size: 30px;
	}

	.name {
		font-size: 30px;
	}

	.specification {
		color: #666666;
		margin-top: 5px;
		font-size: 25px;
	}

	.tags,
	.highlights {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
	}

	.tag,
	.highlight {
		background-color: #f8f8f8;
		color: #333333;
		padding: 5rpx 10rpx;
		margin-right: 10rpx;
		border-radius: 10rpx;
		font-size: 24rpx;
	}

	/* 商品评价 */
	.reviews {
		padding: 20rpx;
		border-top: 1px solid #eeeeee;
	}

	.reviews-title {
		font-size: 28rpx;
		color: #333333;
		font-weight: bold;
	}

	.review {
		margin-top: 10rpx;
		padding-bottom: 20rpx;
	}

	.review-header {
		display: flex;
		justify-content: space-between;
	}

	.review-user {
		font-size: 24rpx;
		color: #666666;
	}

	.review-meta {
		float: right;
		font-size: 22rpx;
		color: #999999;
	}

	.stars .star {
		color: #ffc107;
		font-size: 24rpx;
	}

	.review-text {
		font-size: 24rpx;
		color: #333333;
		margin-top: 10rpx;
	}

	/* 点击收藏和加入购入车动画 */
	.animate {
		animation: bounce 0.3s ease-in-out;
	}

	@keyframes bounce {

		0%,
		100% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.2);
		}
	}

	/* 点击立即购买后遮罩 */
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
	}

	/* 弹窗内容 */
	.popup {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		z-index: 1001;
		padding: 20rpx;
		animation: slideUp 0.3s ease-out;
	}

	/* 弹窗动画 */
	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.popup-title {
		font-size: 28rpx;
		font-weight: bold;
	}

	.popup-close {
		font-size: 28rpx;
		color: #999;
		cursor: pointer;
	}

	.popup-content {
		padding-bottom: 20rpx;
	}

	.popup-option {
		margin-bottom: 20rpx;
	}

	.option-name {
		font-size: 24rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.option-values {
		display: flex;
		flex-wrap: wrap;
	}

	.option-value {
		padding: 10rpx 20rpx;
		border: 1px solid #ccc;
		border-radius: 10rpx;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
		cursor: pointer;
	}

	.option-value.selected {
		background-color: #e60012;
		color: #fff;
		border-color: #e60012;
	}

	.popup-footer {
		text-align: center;
	}

	.btn-confirm {
		width: 100%;
		padding: 15rpx 0;
		background-color: #e60012;
		color: #fff;
		font-size: 24rpx;
		border-radius: 50rpx;
	}

	/* 弹窗增减数量按钮 */
	.quantity-selector {
		float: right;
		margin-right: 25px;
		margin-bottom: 10px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 125px;
		height: 20px;
		border: 1px solid #ccc;
		border-radius: 16px;
		background-color: #f9f9f9;
		overflow: hidden;
	}

	.quantity-btn {
		flex: 1;
		line-height: 36px;
		border: none;
		background: none;
		font-size: 20px;
		font-weight: bold;
		color: #333;
		cursor: pointer;
	}

	.quantity-btn.minus {
		border-right: 1px solid #ccc;
	}

	.quantity-btn.plus {
		border-left: 1px solid #ccc;
	}

	.quantity-value {
		flex: 1;
		text-align: center;
		font-size: 14px;
		color: #333;
	}

	/* 底部导航栏，固定在页面底部 */
	.bottom-nav {
		position: fixed;
		bottom: 0;
		width: 100%;
		display: flex;
		justify-content: space-around;
		padding: 5rpx 0;
		border-top: 1px solid #eeeeee;
		background-color: #ffffff;
	}

	.btn-buy {
		font-size: 25rpx;
		color: #ffffff;
		padding: 15rpx 0;
		width: 30%;
		text-align: center;
		background-color: #e60012;
		border-radius: 50rpx;
		padding: 20rpx 0;
		width: 50%;
	}

	.order-status {
		display: flex;
		justify-content: space-around;
		margin-top: px;
		margin-left: 30px;
	}

	.status-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-left: 30px;
	}

	.status-text {
		font-size: 14px;
		color: #333333;
	}

	.order-icon {
		width: 30px;
		height: 30px;
	}
</style>